import { createAsyncThunk, createSlice } from '@reduxjs/toolkit'
import {
  getAssignTreeList,
  getSelectRoleList
} from '@/service/module/main/system/role-list'

interface ISelectRoleItem {
  value: number
  label: string
}

interface IAssignTree {
  checkList?: any[]
  menuList?: any[]
  menuListLength?: number
}

interface IRoleListState {
  selectRoleList: ISelectRoleItem[]
  assignTreeList: IAssignTree
}

const initialState: IRoleListState = {
  // 下拉框的角色数据：给用户分配角色
  selectRoleList: [],
  // 权限树数据：给角色分配权限
  assignTreeList: {}
}

// 获取下拉框格式的角色数据
export const fetchSelectRoleListAction = createAsyncThunk(
  'fetch/select-role-list',
  async (_, { dispatch }) => {
    const res = await getSelectRoleList()
    dispatch(changeSelectRoleListAction(res.data))
    return res.data
  }
)

// 获取权限树数据
export const fetchAssignTreeListAction = createAsyncThunk(
  'fetch/assign-list',
  async (params: any, { dispatch }) => {
    const res = await getAssignTreeList(params)
    dispatch(changeTreeAssignListAction(res.data))
    return res.data
  }
)

const roleListSlice = createSlice({
  name: 'role-list',
  initialState,
  reducers: {
    changeSelectRoleListAction(state, { payload }) {
      state.selectRoleList = payload
    },
    changeTreeAssignListAction(state, { payload }) {
      state.assignTreeList = payload
    }
  }
})

export const { changeSelectRoleListAction, changeTreeAssignListAction } =
  roleListSlice.actions
export default roleListSlice.reducer
